import sys
import wx
from os import path

from LMG.Utility.constants import * # pylint: disable-msg = W0611,W0401
from LMG.Utility.helpers import fixWindowsName, fixInvalidName

################################################################

class SetDestDialog(wx.Dialog):
    """
    Used to set a torrent's destination
    """
    def __init__(self, torrent, parent = None):

        self.torrent = torrent

        title = _('Change download destination...')

        wx.Dialog.__init__(self, parent, -1, title)

        # May be called with a torrent
        # This dialog is used :
        # 1 - to change the destination (location and name) of an existing torrent (the dialog has an apply button) :
        # 2 - to choose a new destination for a new torrent because the destination is duplicate or badly named (no apply button in this case) :

        if self.torrent.files.isFile():
            indestloc = self.torrent.files.dest
        else:
            indestloc = self.torrent.files.getProcDest(pathonly = True, checkexists = False)
        destloc = path.split(indestloc)[0]
        destname = path.split(indestloc)[1]
        self.currenttorname = self.torrent.getColumnText(COL_TITLE)
        self.torfilename = path.split(self.torrent.src)[1]
        self.newdest = ''

        outerbox = wx.BoxSizer(wx.VERTICAL)

        globalbox = wx.StaticBoxSizer(wx.StaticBox(self, -1, ''), wx.VERTICAL)

        downdestlocbox = wx.StaticBoxSizer(wx.StaticBox(self, -1, _('Set download directory location')), wx.VERTICAL)
        downdestloc = wx.BoxSizer(wx.HORIZONTAL)
        self.downdestloctext = wx.TextCtrl(self, -1, destloc, wx.Point(-1, -1), wx.Size(400, -1))        
        downdestloc.Add(self.downdestloctext, 1)
        downdestlocbtn = wx.Button(self, -1, _('browse'), style = wx.BU_EXACTFIT)
        downdestloc.Add(downdestlocbtn, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT, 5)
        downdestlocbox.Add(downdestloc, 0, wx.EXPAND | wx.TOP, 0)

        if self.torrent.files.isFile():
            downdestnamehead = _('Set download filename')
        else:
            downdestnamehead = _('Set download directory name')
        downdestnamebox = wx.StaticBoxSizer(wx.StaticBox(self, -1, downdestnamehead), wx.VERTICAL)
        downdestname = wx.BoxSizer(wx.HORIZONTAL)
        self.downdestnametext = wx.TextCtrl(self, -1, destname, wx.Point(-1, -1), wx.Size(400, -1))        
        downdestname.Add(self.downdestnametext, 1)
        downdestnamebtn = wx.Button(self, -1, _('browse'), style = wx.BU_EXACTFIT)
        downdestname.Add(downdestnamebtn, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT, 5)
        downdestnamebox.Add(downdestname, 0, wx.EXPAND | wx.TOP, 0)

        globalbox.Add(downdestlocbox, 0, wx.TOP, 6)
        globalbox.Add(downdestnamebox, 0, wx.TOP | wx.EXPAND, 6)

        self.rentorwithdest = wx.CheckBox(self, -1, _('Also change title in list'))
        if utility.config.Read('defrentorwithdest', "boolean"):
            self.rentorwithdest.SetValue(True)
        else:
            self.rentorwithdest.SetValue(False)
        globalbox.Add(self.rentorwithdest, 0, wx.ALL, 5)

        self.movedata = wx.CheckBox(self, -1, _('Move already existing data'))
        globalbox.Add(self.movedata, 0, wx.ALL, 5)

        outerbox.Add(globalbox, 0, wx.TOP, -4)

        buttonbox = wx.BoxSizer(wx.HORIZONTAL)
        okbtn = wx.Button(self, wx.ID_OK, _('OK'))
        okbtn.SetDefault()
        cancelbtn = wx.Button(self, wx.ID_CANCEL, _('Cancel'))
        applybtn = wx.Button(self, wx.ID_APPLY, _('Apply'))
        buttonbox.Add(okbtn, 0, wx.ALL|wx.EXPAND, 5)
        buttonbox.Add(cancelbtn, 0, wx.ALL|wx.EXPAND, 5)
        buttonbox.Add(applybtn, 0, wx.ALL|wx.EXPAND, 5)

        outerbox.Add(buttonbox, 0, wx.ALIGN_RIGHT)

        self.SetAutoLayout(True)
        self.SetSizerAndFit(outerbox)

        # Add events
        self.Bind(wx.EVT_BUTTON, self._onChangeLocation, downdestlocbtn)
        self.Bind(wx.EVT_BUTTON, self._onChangeName, downdestnamebtn)
        self.Bind(wx.EVT_BUTTON, self._onApply, applybtn)
        self.Bind(wx.EVT_BUTTON, self._onOK, okbtn)
        self.Bind(wx.EVT_BUTTON, self._onCancel, cancelbtn)
        self.Bind(wx.EVT_CLOSE, self._onCancel)
        
        # What are the current values for the torrent
        self.currentvalues = {}
        self.currentvalues['destloc'] = self.downdestloctext.GetValue()
        self.currentvalues['destname'] = self.downdestnametext.GetValue()
        

        accelTable = wx.AcceleratorTable([(wx.ACCEL_NORMAL, wx.WXK_ESCAPE, cancelbtn.GetId())])
        self.SetAcceleratorTable(accelTable)


    def _getPath(self):
        return self.newdest

    def _onChangeLocation(self, event):
        dlg = wx.DirDialog(self, 
                           _('Choose new download directory location'), 
                           self.downdestloctext.GetValue(), 
                           style = wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
        result = dlg.ShowModal()
        dest = dlg.GetPath()
        dlg.Destroy()
        if result == wx.ID_OK:
            self.downdestloctext.SetValue(dest)

    def _onChangeName(self, event = None):
        if self.torrent.files.isFile():
            dlg = wx.FileDialog(self, 
                               _('Choose new download file name :'), 
                               self.downdestloctext.GetValue(), 
                               self.downdestnametext.GetValue(), 
                               _('All Files') + ' (*.*)|*.*', 
                               wx.SAVE)
        else:
            dlg = wx.DirDialog(self, 
                              _('Choose new download directory name :'), 
                              path.join(self.downdestloctext.GetValue(), self.downdestnametext.GetValue()), 
                              style = wx.DD_DEFAULT_STYLE | wx.DD_NEW_DIR_BUTTON)
        result = dlg.ShowModal()
        dest = dlg.GetPath()
        dlg.Destroy()
        if result == wx.ID_OK:
            self.downdestloctext.SetValue(path.split(dest)[0])
            self.downdestnametext.SetValue(path.split(dest)[1])

    def _onCancel(self, event = None):
        self.EndModal(wx.ID_CANCEL)

    def _onApply(self, event = None):
        newdowndestloc = self.downdestloctext.GetValue().rstrip()
        newdowndestname = self.downdestnametext.GetValue().rstrip()
        
        # Values haven't changed -- no need to do anything here
        if ((newdowndestloc == self.currentvalues['destloc']) and
            (newdowndestname == self.currentvalues['destname'])):
            return True
        
        # Check if file and folder names are valid ones in Windows
        if sys.platform == 'win32':
            # We erase the final '\' except for a path like 'X:\'
            newdowndestloc_orig = newdowndestloc
            if newdowndestloc and newdowndestloc[-1] == '\\' and (len(newdowndestloc) < 2 or newdowndestloc[-2] != ':'):
                newdowndestloc = newdowndestloc[:-1]
            if not utility.checkWinPath(self, newdowndestloc_orig):
                return False
            fixedname = fixInvalidName(newdowndestname)
            if fixedname != newdowndestname:
                dlg = wx.MessageDialog(self, 
                                       newdowndestname + '\n' + \
                                       _('This name cannot be used as a Windows file or folder name.') + '\n'+ \
                                       _('Suggested corrected name :') + '\n\n' + \
                                       fixedname, 
                                       _('Error'), wx.ICON_ERROR)
                dlg.ShowModal()
                dlg.Destroy()
                return False

        self.newdest = path.join(newdowndestloc, newdowndestname)
        # Change the destination
        
        renamewithdest = self.rentorwithdest.GetValue()
        
        if self.movedata.GetValue():
            self.torrent.files.move(newdowndestloc, newdowndestname, renamewithdest)
        else:
            self.torrent.files.changeProcDest(self._getPath(), renamewithdest)

        # Keep track of the current values that we've saved
        self.currentvalues['destloc'] = newdowndestloc
        self.currentvalues['destname'] = newdowndestname

        return True

    def _onOK(self, event = None):
        if self._onApply():
            self.EndModal(wx.ID_OK)
